package cn.lei.uicontrols;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;

import java.util.Timer;
import java.util.TimerTask;

public class AtyUsingProgressBar extends AppCompatActivity {

    private ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aty_using_progress_bar);

        mProgressBar = (ProgressBar) findViewById(R.id.progressBar4);
        mProgressBar.setMax(100);
        mProgressBar.setProgress(50);
    }

    @Override
    protected void onResume() {
        super.onResume();
        stratTimer();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopTimer();
    }

    private int progress = 0;

    public void stratTimer () {
        if (timer == null) {
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    if (progress == 100) {
                        progress = 0;
                    }
                    progress++;
                    mProgressBar.setProgress(progress);
                }
            };
            timer.schedule(task, 1000, 1000);
        }
    }

    public void stopTimer() {
        if (timer != null) {
            task.cancel();
            timer.cancel();

            task = null;
            timer = null;
        }
    }

    private Timer timer = null;
    private TimerTask task = null;
}
